import { EmitType } from '@/global'
import { ComputedRef, unref, watch } from 'vue'
import { FormProps, FormSchema } from '../types/form'
import type { AdvanceState } from '../types/formAction'
interface UseAdvancedContext {
  advanceState: AdvanceState
  getProps: ComputedRef<FormProps>
  getSchema: ComputedRef<FormSchema[]>
  emit: EmitType
}
export default function ({ advanceState, getSchema, getProps, emit }: UseAdvancedContext) {
  watch(
    [() => unref(getSchema), () => advanceState.isAdvanced],
    () => {
      const { showAdvancedButton } = unref(getProps)
      if (showAdvancedButton) {
        updateAdvanced()
      }
    },
    { immediate: true }
  )
  function updateAdvanced() {
    for (const schema of unref(getSchema)) {
      if (Object.prototype.hasOwnProperty.call(schema, 'isAdvanced')) {
        schema.isAdvanced = !schema.isAdvanced
      }
    }
    emit('advanced-change')
  }
  function handleToggleAdvanced() {
    advanceState.isAdvanced = !advanceState.isAdvanced
  }
  return { handleToggleAdvanced }
}
